import java.util.ArrayList;
import java.util.List;

/**
 * 面试题 08.04. 幂集
 * https://leetcode-cn.com/problems/power-set-lcci/
 */
public class Solutions_mianshi_08_04 {
    public static void main(String[] args) {
        int[] nums1 = {1, 2, 3};  // output: {{3}, {1}, {2}, {1, 2, 3}, {1, 3}, {2, 3}, {1, 2}, {}}

        List<int[]> inputs = new ArrayList<>();
        inputs.add(nums1);

        for (int[] input : inputs) {
            List<List<Integer>> result = subsets(input);
            System.out.println(result);
        }
    }

    private static List<List<Integer>> res;
    private static List<Integer> list;
    /**
     * 解题思路：回溯法
     * 无重复元素，即直接递归即可，无需判断
     */
    public static List<List<Integer>> subsets(int[] nums) {
        res = new ArrayList<>();
        list = new ArrayList<>();

        backtrack(nums, 0);
        return res;
    }

    public static void backtrack(int[] nums, int idx) {
        // 添加子集
        res.add(new ArrayList<>(list));
        for (int i = idx; i < nums.length; i++) {
            // 添加元素
            list.add(nums[i]);
            // 递归下一层
            backtrack(nums, i + 1);
            // 回溯操作：移除元素
            list.remove(list.size() - 1);
        }
    }
}
